function getsec(str){
    var str1=str.substring(1,str.length)*1;
    var str2=str.substring(0,1);
    if (str2=="s"){
        return str1*1000;
    }else if (str2=="h"){
        return str1*60*60*1000;
    }else if (str2=="d"){
        return str1*24*60*60*1000;
    }
}
var BASE_URL = document.scripts[document.scripts.length - 1].src.substring(0, document.scripts[document.scripts.length - 1].src.lastIndexOf("/") + 1);
window.BASE_URL = BASE_URL; //取加载页面所在的dom的第一个js的路径的基础地址



layui.define(["jquery","layer",'tableSelect','upload'],function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
    var layer = layui.layer;
    var upload = layui.upload;
    var tableSelect = layui.tableSelect;
    var $ = layui.jquery;
    var util = {
        data:{
            valid_data:{}
        },
        msg :{
            // 成功消息
            success: function (msg, callback) {
                if (callback === undefined) {
                    callback = function () {
                    }
                }
                var index = layer.msg(msg, {icon: 1, shade: 0, scrollbar: false, time: 2000, shadeClose: true}, callback);
                return index;
            },
            // 失败消息
            error: function (msg, callback) {
                if (callback === undefined) {
                    callback = function () {
                    }
                }
                var index = layer.msg(msg, {icon: 2, shade: 0, scrollbar: false, time: 3000, shadeClose: true}, callback);
                return index;
            },
            // 警告消息框
            alert: function (msg, callback) {
                var index = layer.alert(msg, {end: callback, scrollbar: false});
                return index;
            },
            // 对话框
            confirm: function (msg, ok, no) {
                var index = layer.confirm(msg, {title: '操作确认', btn: ['确认', '取消']}, function () {
                    typeof ok === 'function' && ok.call(this);
                }, function () {
                    typeof no === 'function' && no.call(this);
                    self.close(index);
                });
                return index;
            },
            // 消息提示
            tips: function (msg, time, callback) {
                var index = layer.msg(msg, {time: (time || 3) * 1000, shade: 0, end: callback, shadeClose: true});
                return index;
            },
            // 加载中提示
            loading: function (msg, callback) {
                var index = msg ? layer.msg(msg, {icon: 16, scrollbar: false, shade: 0, time: 0, end: callback}) : layer.load(2, {time: 0, scrollbar: false, shade: 0, end: callback});
                return index;
            },
            // 关闭消息框
            close: function (index) {
                return layer.close(index);
            }

        },
        image:function(data) {
        var option = {};
        option.imageWidth = 200;
        option.imageHeight =  40;
        option.imageSplit =  ',';
        option.title =  option.field;
        var title = data[option.title];
        // return '<img style="max-width: ' + option.imageWidth + 'px; max-height: ' + option.imageHeight + 'px;" src="' + value + '" data-image="' + title + '">';
        return '<img style="max-width: ' + option.imageWidth + 'px; max-height: ' + option.imageHeight + 'px;" src="' + data.url + '" data-image="' + title + '">';
    },
        upload:function(init) {
            if(!init)init = util.init;
            var uploadList = document.querySelectorAll("[data-upload]");
            var uploadSelectList = document.querySelectorAll("[data-upload-select]");

            if (uploadList.length > 0) {
                $.each(uploadList, function (i, v) {
                    var exts = $(this).attr('data-upload-exts'),
                        uploadName = $(this).attr('data-upload'),//上传input组件名字name保持一致
                        uploadNumber = $(this).attr('data-upload-number'),
                        uploadSign = $(this).attr('data-upload-sign');//可以自定义分隔符 默认为|
                    exts = exts || init.upload_exts;
                    uploadNumber = uploadNumber || 'one';
                    uploadSign = uploadSign || ',';
                    var elem = "input[name='" + uploadName + "']",
                        uploadElem = this;
                    //如果已经初始过了则不再初始,未初始则存入初始
                   if(util.data.valid_data[uploadName])return;
                    util.data.valid_data[uploadName] = uploadName;
                    // 监听上传事件
                    upload.render({
                        elem: this,
                        url: init.upload_url,
                        accept: 'file',
                        exts: exts,
                        done: function (res) {
                            if (res.code === 200 && res.data.errcode === 0) {
                                var url = res.data.data.src;
                                if (uploadNumber !== 'one') {
                                    var oldUrl = $(elem).val();
                                    if (oldUrl !== '') {
                                        url = oldUrl + uploadSign + url;
                                    }
                                }
                                util.msg.success(res.msg, function () {
                                    $(elem).val(url);
                                    $(elem).trigger("input");
                                });
                            } else {
                                util.msg.error(res.msg);
                            }
                            return false;
                        }
                    });
                    // 监听上传input值变化
                    $(elem).bind("input propertychange", function (event) {
                        var urlString = $(this).val(),
                            urlArray = urlString.split(uploadSign),
                            uploadMime =$('#select_'+$(uploadElem).attr('data-upload')).attr('data-upload-mimetype'),//默认为image/*
                            uploadIcon = $(uploadElem).attr('data-upload-icon'),//默认为file
                            uploadIcon = uploadIcon || "file";
                        $('#bing-' + uploadName).remove();
                        //保证是图片才会渲染出来DIV
                        if (urlString.length > 0 && uploadMime && (uploadMime.indexOf("image") != -1)) {
                            var parant = $(this).parent('div');
                            var liHtml = '';
                            $.each(urlArray, function (i, v) {
                                liHtml += '<li><a><img src="' + v + '" data-image  onerror="this.src=\'' + BASE_URL + 'admin/images/upload-icons/' + uploadIcon + '.png\';this.onerror=null"></a><small style="cursor: pointer;" class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                            });
                            parant.after('<ul id="bing-' + uploadName + '" class="layui-input-block layuimini-upload-show">\n' + liHtml + '</ul>');
                        }

                    });

                    // 非空初始化图片显示
                    if ($(elem).val() !== '') {
                        $(elem).trigger("input");
                        //触发一下该input的input事件
                        //$(elem)[0].dispatchEvent(new Event('input'));
                    }
                });

                // 监听上传文件的删除角标的单击事件
                $('body').on('click', '[data-upload-delete]', function () {
                    var uploadName = $(this).attr('data-upload-delete'),
                        deleteUrl = $(this).attr('data-upload-url'),
                        sign = $(this).attr('data-upload-sign');
                    var confirm = util.msg.confirm('确定删除？', function () {
                        var elem = "input[name='" + uploadName + "']";
                        var currentUrl = $(elem).val();
                        var url = '';
                        if (currentUrl !== deleteUrl) {
                            url = currentUrl.replace(sign + deleteUrl, '');
                            $(elem).val(url);
                            $(elem).trigger("input");
                        } else {
                            $(elem).val(url);
                            $('#bing-' + uploadName).remove();
                        }
                        util.msg.close(confirm);
                    });
                    return false;
                });
            }

            if (uploadSelectList.length > 0) {
                $.each(uploadSelectList, function (i, v) {
                    var exts = $(this).attr('data-upload-exts'),
                        uploadName = $(this).attr('data-upload-select'),
                        uploadNumber = $(this).attr('data-upload-number'),
                        uploadSign = $(this).attr('data-upload-sign');
                    exts = exts || init.upload_exts;
                    uploadNumber = uploadNumber || 'one';
                    uploadSign = uploadSign || ',';
                    var selectCheck = uploadNumber === 'one' ? 'radio' : 'checkbox';
                    var elem = "input[name='" + uploadName + "']",
                        uploadElem = $(this).attr('id');

                    tableSelect.render({
                        elem: "#" + uploadElem,
                        checkedKey: 'id',
                        searchType: 'more',
                        searchList: [
                            {searchKey: 'title', searchPlaceholder: '请输入文件名'},
                        ],
                        table: {
                            url: init.get_upload_files,
                            cols: [[
                                {type: selectCheck},
                                {field: 'id', title: 'ID'},
                                {field: 'url', minWidth: 80, search: false, title: '图片信息', imageHeight: 40, align: "center", templet: util.image},
                                {field: 'original_name', width: 150, title: '文件原名', align: "center"},
                                {field: 'mime_type', width: 120, title: 'mime类型', align: "center"},
                                {field: 'create_time', width: 200, title: '创建时间', align: "center", search: 'range'},
                            ]]
                        },
                        done: function (e, data) {
                            var urlArray = [];
                            $.each(data.data, function (index, val) {
                                urlArray.push(val.url)
                            });
                            var url = urlArray.join(uploadSign);
                            util.msg.success('选择成功', function () {
                                $(elem).val(url);
                                $(elem).trigger("input");
                                //触发一下该input的input事件
                                if($(elem)[0]) $(elem)[0].dispatchEvent(new Event('input'));
                                 // $(elem).dispatchEvent(new Event('input'));
                            });
                        }
                    })

                });

            }
        },
        init :{
            upload_url: '/manage/publicCommon/upload',//layui.upload上传网址
            upload_exts: 'doc|gif|ico|icon|jpg|mp3|mp4|p12|pem|png|rar',
            get_upload_files: '/manage/publicCommon/getUploadFiles',
            upload_editor: '/manage/publicCommon/uploadEditor',//编辑器里面的上传URL
        },
        setEditorData:function (dataField) {
            // // 富文本数据处理
            // var editorList = document.querySelectorAll(".editor");
            // if (editorList.length > 0) {
            //     $.each(editorList, function (i, v) {
            //         var name = $(this).attr("name");
            //         dataField[name] = CKEDITOR.instances[name].getData();
            //     });
            // }
            // return dataField;
        },
        editor: function () {
            // var editorList = document.querySelectorAll(".editor");
            // if (editorList.length > 0) {
            //     $.each(editorList, function (i, v) {
            //         CKEDITOR.replace(
            //             $(this).attr("name"),
            //             {
            //                 height: $(this).height(),
            //                 filebrowserImageUploadUrl: init.upload_editor,
            //             });
            //     });
            // }
        },
        refresh:function(init) {
            if(!init)init = util.init;
            var uploadList = document.querySelectorAll("[data-upload]");
            if (uploadList.length > 0) {
                $.each(uploadList, function (i, v) {
                    var exts = $(this).attr('data-upload-exts'),
                        uploadName = $(this).attr('data-upload'),//上传input组件名字name保持一致
                        uploadNumber = $(this).attr('data-upload-number'),
                        uploadSign = $(this).attr('data-upload-sign');//可以自定义分隔符 默认为|
                    exts = exts || init.upload_exts;
                    uploadNumber = uploadNumber || 'one';
                    uploadSign = uploadSign || ',';
                    var elem = "input[name='" + uploadName + "']",
                        uploadElem = this;
                    $(elem).trigger("input");
                    // 监听上传input值变化
                    $(elem).bind("input propertychange", function (event) {
                        var urlString = $(this).val(),
                            urlArray = urlString.split(uploadSign),
                            uploadMime =$('#select_'+$(uploadElem).attr('data-upload')).attr('data-upload-mimetype'),//默认为image/*
                            uploadIcon = $(uploadElem).attr('data-upload-icon'),//默认为file
                            uploadIcon = uploadIcon || "file";
                        $('#bing-' + uploadName).remove();
                        //保证是图片才会渲染出来DIV
                        if (urlString.length > 0 && uploadMime && (uploadMime.indexOf("image") != -1)) {
                            var parant = $(this).parent('div');
                            var liHtml = '';
                            $.each(urlArray, function (i, v) {
                                liHtml += '<li><a><img src="' + v + '" data-image  onerror="this.src=\'' + BASE_URL + 'admin/images/upload-icons/' + uploadIcon + '.png\';this.onerror=null"></a><small style="cursor: pointer;" class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                            });
                            parant.after('<ul id="bing-' + uploadName + '" class="layui-input-block layuimini-upload-show">\n' + liHtml + '</ul>');
                        }

                    });

                    // 非空初始化图片显示
                    if ($(elem).val() !== '') {
                        $(elem).trigger("input");
                    }
                });
            }
        },
    };
    layui.addcss('../../../js/lay-module/bwutil/bwutil.css');
    //输出接口
    exports('bwimage', util);
});



